package com.kizuki.thread;

import org.junit.Test;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

public class TestSpinlock {

    @Test
    public void test() throws InterruptedException {
        MyLock lock = new MyLock();

        new Thread(()->{
            lock.myLock();
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.myUnlock();
            }
        }, "A").start();

        new Thread(()->{
            lock.myLock();
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.myUnlock();
            }
        }, "B").start();

        TimeUnit.SECONDS.sleep(4);
    }

}

// 自旋锁
class MyLock{
    private AtomicReference<Thread> threadAtomicReference = new AtomicReference<>();

    @Test
    public void myLock(){
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName() + " myLock");
        while (!threadAtomicReference.compareAndSet(null, thread)) {

        }
    }

    @Test
    public void myUnlock(){
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName() + " myUnlock");
        threadAtomicReference.compareAndSet(thread, null);
    }


}
